package net.tribal.comic.services

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
import net.tribal.comic.utils.ImageTools

class FileService {

    boolean transactional = true

    
    /**
     * Generate Random Name
     */
    def generateRandomString = { length ->
    	def max = (CH.config.comics.availChars).size()
    	def rnd = new Random()  
    	def sb = new StringBuilder()  
    	length.times { sb.append(CH.config.comics.availChars[rnd.nextInt(max)]) }
    	sb.toString()
    }
    
    
    /**
     * Inicialitzem l'entorn
     * 
     * @return void
     */
    def init() {
    	//	Created By Chris Rauber --> http://www.chrisrauber.com/blog/default.aspx
    	('A'..'Z').each { CH.config.comics.availChars << it.toString() }		//	create the list of available characters  
        3.times { (0..9).each { CH.config.comics.availChars << it.toString() } }		//  even it out to about the same odds of getting a char or a number
        
        //	Crea la estructura de carpetas
    	def path = CH.config.comics.path
    	createPath(path)
    	def folders = CH.config.comics.fileFolders
    	folders.each() { createPath( path+it ) }
    }
	
	
    /**
     * Create a path into file system
     * 
     * @param path
     * @return void
     */
    def createPath( path ) {
    	if ( !( new File( path ) ).exists() ) {
    		( new File( path ) ).mkdir()
			log.debug "Se crea el directorio: " + path 
		}
    }
	
	
    /**
     * Validates the format, type and size of size
     * 
     * @param file
     * @param fileSizeMax
     * @return String [ok:extension file, ko:message error]
     */
    def validate( file, fileSizeMax ) {
    	//-------1� validem que el tamany del fitxer
    	if(file.getSize() > fileSizeMax){
    		return [error:"El tama�o es demasiado grande"]
    	}
    	
    	//-------2� mirar que sigui image
    	def fileType = file.getContentType().split("/")[0]
    	if(fileType.toUpperCase() != "IMAGE") {
    		return [error:"No es un fichero de imagen"]	//I18N
    	}
    	
    	//-------3� mirar que sigui dels formats permessos
    	def extensionFile = file.getContentType().split("/")[1]
    	if(!CH.config.comics.allowedTypeFiles.grep(extensionFile.toUpperCase())) {
    		return [error:"No es un tipo de fichero valido"]
    	}
    	
    	return [ext:extensionFile]
    }
    
    
    
    /**
     * Guarda el fichero en el disco con un nombre aleatorio
     * 
     * @param file
     * @param path
     * @param ext
     * @return String [ok:file name, ko:null]
     */
    def addFile(file, path, ext) {
    	def random
    	def existsFile = true
    	def newFile
    	try {
    		while(existsFile) {
    			random = generateRandomString(8)
	    		newFile = new File(CH.config.comics.path + path + random + "." + ext)
	    		if ( !newFile.exists() ) { existsFile = false }
    		}
    		file.transferTo( newFile )
    		ImageTools.resize(new File(CH.config.comics.path + path + random +"."+ ext), new File(CH.config.comics.path + path + random +"_thumbnail."+ ext), 300, 0.3f)
    		return random
    		
    	} catch (e) {
    		if ( file != null && !file.isEmpty() ) {
    			this.removeFile(path, random + "." + ext)
			}
    		return null 
    	}
    }
	
	
    /**
     * Remove images from file system
     * 
     * @param path
     * @param name
     * @return boolean [ok:true, ko:false]
     */
    def removeFile(path, name) {
		if(!name) { return false }
		try {
			// Borrem la imatge original
			(new File(CH.config.comics.path + path + name)).delete()
			
			// Borrem la imatge en miniatura
			def nameThumbnail = name.tokenize(".")
			name = nameThumbnail[0] + "_thumbnail." + nameThumbnail[1]
			(new File(CH.config.comics.path + path + name)).delete()
			
		} catch (e) { return false }
	
		return true
    }
}